package tongwentongshu.com.app.activity;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.tencent.imsdk.TIMConversationType;
import com.tencent.imsdk.TIMFriendshipManager;
import com.tencent.imsdk.TIMUserProfile;
import com.tencent.imsdk.TIMValueCallBack;
import com.tencent.imsdk.ext.sns.TIMAddFriendRequest;
import com.tencent.imsdk.ext.sns.TIMFriendResult;
import com.tencent.imsdk.ext.sns.TIMFriendshipManagerExt;


import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import tongwentongshu.com.app.App;
import tongwentongshu.com.app.R;
import tongwentongshu.com.app.activityim.ChatActivity;
import tongwentongshu.com.app.activityim.HomeActivity;
import tongwentongshu.com.app.adapter.NullAdapter;
import tongwentongshu.com.app.adapter.ReadingNotesAdapter;
import tongwentongshu.com.app.adapter.ReadingPeopleAdapter;
import tongwentongshu.com.app.bean.AppItem;
import tongwentongshu.com.app.bean.BookDetailsBean;
import tongwentongshu.com.app.bean.TextEvent;
import tongwentongshu.com.app.contract.CallBackColonyContract;
import tongwentongshu.com.app.contract.ReadingDetailsContract;
import tongwentongshu.com.app.db.Cache;
import tongwentongshu.com.app.dialog.AlertUtils;
import tongwentongshu.com.app.dialog.ShareUtils;
import tongwentongshu.com.app.presenter.ReadingDetailsPresenter;
import tongwentongshu.com.app.utils.AmapUtil;
import tongwentongshu.com.app.utils.GlideUtil;
import tongwentongshu.com.app.utils.NetUtils;
import tongwentongshu.com.app.utils.ToastUtil;
import tongwentongshu.com.app.view.RoundImageView;

/**
 * Created by XiongBin on 2017/7/3.
 */

public class ReadingDetailsActivity extends BaseActivity implements ReadingDetailsContract.View, View.OnClickListener, SwipeRefreshLayout.OnRefreshListener {

    @BindView(R.id.title_share)
    ImageView share;
    @BindView(R.id.rv_list)
    RecyclerView mRecyclerView;
    @BindView(R.id.swipeLayout)
    SwipeRefreshLayout mSwipeRefreshLayout;
    @BindView(R.id.tv_operation)
    TextView operationText;//操作文本
    @BindView(R.id.tv_collection)
    TextView collectionText;//收藏文本
    @BindView(R.id.tv_reading_when_long)
    TextView whenLongText;//阅读时间长度
    @BindView(R.id.ll_operation)
    LinearLayout operation;//操作按钮
    @BindView(R.id.ll_collection)
    LinearLayout collection;//收藏按钮
    @BindView(R.id.iv_collection)
    ImageView collectionImg;//收藏按钮图标
    @BindView(R.id.ll_call)
    LinearLayout call;//联系读者
    @BindView(R.id.rel_call)
    RelativeLayout callRel;//联系读者
    @BindView(R.id.ll_msg)
    LinearLayout chat;//聊天
    @BindView(R.id.ll_renewal)
    LinearLayout renewal;//续期
    @BindView(R.id.rel_renewal)
    RelativeLayout renewalRel;//续期
    @BindView(R.id.iv_operation)
    ImageView ivOperation;
    @BindView(R.id.v_l1)
    View v1;
    @BindView(R.id.v_l2)
    View v2;

    private boolean operation_Judge = true;

    private NullAdapter nullAdapter;
    private ReadingNotesAdapter readingNotesAdapter;
    private ReadingPeopleAdapter readingPeopleAdapter;
    private ReadingDetailsPresenter readingDetailsPresenter;
    private BookDetailsBean msg;
    private String pagerType;
    private String bookId;
    private boolean pager_Judge;//true是首页进入，false是个人中心进入

    private String STATUS = "1";
    private boolean first = true;

    @Override
    protected int getLayoutResourceId() {
        return R.layout.activity_reading_details;
    }

    @Override
    protected int getTitleId() {
        return R.string.reading_details;
    }

    @Override
    protected void initView() {

        initPagerType();
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        App.getApplication().addReadingActivity(this);
        ViewGroup.LayoutParams linearParams = (ViewGroup.LayoutParams) whenLongText.getLayoutParams();
        linearParams.width = (int) NetUtils.getDisplayMetrics((Activity) mContext, NetUtils.DM_WIDTH) / 2;
        whenLongText.setLayoutParams(linearParams); //使设置好的布局参数应用到控件
        share.setImageResource(R.drawable.home_share);
        call.setOnClickListener(this);
        renewal.setOnClickListener(this);
        operation.setOnClickListener(this);
        collection.setOnClickListener(this);
        chat.setOnClickListener(this);
        share.setOnClickListener(this);
    }

    void initPagerType() {
        pagerType = getIntent().getExtras().getString("pagerType");
        bookId = getIntent().getExtras().getString("bookId");
        pager_Judge = getIntent().getExtras().getBoolean("pager_Judge");
    }

    public void onEventMainThread(TextEvent result) {
        myNote.setText(result.getNote());
    }

    @Override
    protected void initData() {

    }

    private View basicView;
    private View ownerView;
    private View noteView;

    @Override
    public String getBookId() {
        return bookId;
    }

    @Override
    public String getFollowId() {
        if (status_type.equals("6"))
            return msg.getData().getBook_read_user_id();
        else
            return msg.getData().getCurrentuserid();
    }

    @Override
    public String getLogId() {
        return msg.getData().getLogid();
    }

    @Override
    public String getStatus() {
        return STATUS;
    }

    private TextView status;

    @Override
    public View getBasicView() {
        basicView = getLayoutInflater().inflate(R.layout.reading_details_book, (ViewGroup) mRecyclerView.getParent(), false);
        status = (TextView) basicView.findViewById(R.id.tv_book_status);
        TextView bookName = (TextView) basicView.findViewById(R.id.tv_book_name);
        bookName.setText("【" + msg.getData().getBooktype() + "】" + msg.getData().getBookname());//图书名称
        TextView bookOwner = (TextView) basicView.findViewById(R.id.tv_book_owner);
        bookOwner.setText(msg.getData().getPublishnick() + "  " + msg.getData().getPublishtime());//图书发布人
//        TextView bookShareTime = (TextView) view.findViewById(R.id.tv_book_share_time);
//        bookShareTime.setText(msg.getData().getPublishtime());//图书发布时间
        TextView bookInfo = (TextView) basicView.findViewById(R.id.tv_book_info);
        TextView readerTxt = (TextView) basicView.findViewById(R.id.tv_reading_complete);
        bookInfo.setText(msg.getData().getBookdesc());//图书简介
        ImageView userImg = (ImageView) basicView.findViewById(R.id.iv_book_image);
        GlideUtil.setImage(mContext, msg.getData().getBookpicurl(), R.drawable.default_graph, R.drawable.default_graph, userImg);
        RecyclerView read_people = (RecyclerView) basicView.findViewById(R.id.ll_read_people);


        read_people.setLayoutManager(new GridLayoutManager(this, 9));

//        View empty = getLayoutInflater().inflate(R.layout.empty_reader, (ViewGroup) mRecyclerView.getParent(), false);
//        readingPeopleAdapter.setEmptyView(empty);
        if (msg.getData().getPersoninfo() != null && msg.getData().getPersoninfo().size() > 0) {
            readingPeopleAdapter = new ReadingPeopleAdapter(msg.getData().getPersoninfo());
            read_people.setAdapter(readingPeopleAdapter);
            read_people.addOnItemTouchListener(new OnItemClickListener() {
                @Override
                public void onSimpleItemClick(final BaseQuickAdapter adapter, final View view, final int position) {
                    showUser(msg.getData().getPersoninfo().get(position).getPersonid());
                }
            });
            read_people.setVisibility(View.VISIBLE);
        } else {
            readerTxt.setText("暂时没有人读过");
            read_people.setVisibility(View.GONE);
        }

        return basicView;
    }

    private TextView reading_time;

    @Override
    public View getOwnerView() {
        ownerView = getLayoutInflater().inflate(R.layout.reading_details_owner, (ViewGroup) mRecyclerView.getParent(), false);
        reading_time = (TextView) ownerView.findViewById(R.id.tv_reader_time);
        TextView userName = (TextView) ownerView.findViewById(R.id.tv_owner_name);
        userName.setText(msg.getData().getCurrentusernick());//当前用户名称
//        TextView userReadingTime = (TextView) ownerView.findViewById(R.id.tv_owner_reading_time);
//        userReadingTime.setText(msg.getData().getReadingtime());//阅读时间
        TextView userLocation = (TextView) ownerView.findViewById(R.id.tv_location);
        userLocation.setText(msg.getData().getNow_book_postition());//图书位置
        ImageView userSex = (ImageView) ownerView.findViewById(R.id.iv_user_sex);//当前读者性别
        if (msg.getData().getCurrentusersex().equals("1")) {
            userSex.setImageResource(R.drawable.mr);
        } else if (msg.getData().getCurrentusersex().equals("0")) {
            userSex.setImageResource(R.drawable.xx);
        } else {
            userSex.setImageResource(R.drawable.miss);
        }
        RoundImageView userPic = (RoundImageView) ownerView.findViewById(R.id.iv_user_image);//当前读者头像
        GlideUtil.setImage(mContext, msg.getData().getCurrentuserheader(), R.drawable.head_img, R.drawable.head_img, userPic);
        userPic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showUser(msg.getData().getCurrentuserid());
            }
        });
        final TextView followTv = (TextView) ownerView.findViewById(R.id.tv_follow);
        final ImageView followIv = (ImageView) ownerView.findViewById(R.id.iv_follow);
        LinearLayout followLl = (LinearLayout) ownerView.findViewById(R.id.ll_follow);

        isFollow(followIv, followTv, String.valueOf(msg.getData().getIsattention()));
        followLl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Cache.LoginVer(mContext))
                    return;
                readingDetailsPresenter.follow(String.valueOf(msg.getData().getIsattention() + 1), new CallBackColonyContract.OnOperation() {
                    @Override
                    public void OperationCallBack(String index) {
                        int status = msg.getData().getIsattention();
                        if (status == 1) {
                            status = 0;
                        } else {
                            status = 1;
                        }
                        msg.getData().setIsattention(status);
                        isFollow(followIv, followTv, String.valueOf(msg.getData().getIsattention()));
                    }
                });
            }
        });

        RecyclerView read_people = (RecyclerView) ownerView.findViewById(R.id.ll_read_people);
        TextView noteText = (TextView) ownerView.findViewById(R.id.tv_note_title);
        if (msg.getData().getContentarray().size() > 0) {
            read_people.setLayoutManager(new LinearLayoutManager(this));
            readingNotesAdapter = new ReadingNotesAdapter(mContext, msg.getData().getContentarray());
            read_people.setAdapter(readingNotesAdapter);
        } else {
            noteText.setVisibility(View.GONE);
            read_people.setVisibility(View.GONE);
        }

        RelativeLayout location = (RelativeLayout) ownerView.findViewById(R.id.rel_location);
        if (bookstatus.equals("2"))
            location.setVisibility(View.GONE);
        location.setOnClickListener(this);

        return ownerView;
    }

    private LinearLayout editBtn;
    private TextView myNote;
    private RelativeLayout relNote;//笔记布局

    @Override
    protected void onResume() {
        super.onResume();

        readingDetailsPresenter = new ReadingDetailsPresenter(this, this);
        if (!first)
            onRefreshJudge = true;
        readingDetailsPresenter.initReadingDetails(mContext);
    }

    @Override
    public View getMyNoteView() {
        noteView = getLayoutInflater().inflate(R.layout.reading_details_note, (ViewGroup) mRecyclerView.getParent(), false);
        reading_time = (TextView) noteView.findViewById(R.id.tv_reader_time);
        editBtn = (LinearLayout) noteView.findViewById(R.id.ll_note_edit);
        relNote = (RelativeLayout) noteView.findViewById(R.id.rel_note);
        LinearLayout perLL = (LinearLayout) noteView.findViewById(R.id.ll_per);
        RelativeLayout location = (RelativeLayout) noteView.findViewById(R.id.rel_location);

        if (status_type.equals("1") || status_type.equals("6")) {
            perLL.setVisibility(View.VISIBLE);
            TextView userName = (TextView) noteView.findViewById(R.id.tv_owner_name);
            TextView userLocation = (TextView) noteView.findViewById(R.id.tv_location);
            TextView inf = (TextView) noteView.findViewById(R.id.tv_info);
            ImageView userSex = (ImageView) noteView.findViewById(R.id.iv_user_sex);//当前读者性别
            RoundImageView userPic = (RoundImageView) noteView.findViewById(R.id.iv_user_image);//当前读者头像

            if (status_type.equals("6")) {
                inf.setText("当前预约的小伙伴儿：");
                userName.setText(msg.getData().getBook_read_user_name());//当前用户名称
                if (msg.getData().getBook_read_user_sex().equals("1")) {
                    userSex.setImageResource(R.drawable.mr);
                } else if (msg.getData().getBook_read_user_sex().equals("0")) {
                    userSex.setImageResource(R.drawable.xx);
                } else {
                    userSex.setImageResource(R.drawable.miss);
                }
                location.setVisibility(View.GONE);
                GlideUtil.setImage(mContext, msg.getData().getBook_read_user_head(), R.drawable.head_img, R.drawable.head_img, userPic);
            } else if (status_type.equals("1")) {
                userName.setText(msg.getData().getCurrentusernick());//当前用户名称
                if (msg.getData().getCurrentusersex().equals("1")) {
                    userSex.setImageResource(R.drawable.mr);
                } else if (msg.getData().getBook_read_user_sex().equals("0")) {
                    userSex.setImageResource(R.drawable.xx);
                } else {
                    userSex.setImageResource(R.drawable.miss);
                }
                GlideUtil.setImage(mContext, msg.getData().getCurrentuserheader(), R.drawable.head_img, R.drawable.head_img, userPic);
                location.setOnClickListener(this);
            }
            userLocation.setText(msg.getData().getNow_book_postition());//图书位置
            userPic.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    showUser(getFollowId());
                }
            });
            final TextView followTv = (TextView) noteView.findViewById(R.id.tv_follow);
            final ImageView followIv = (ImageView) noteView.findViewById(R.id.iv_follow);
            LinearLayout followLl = (LinearLayout) noteView.findViewById(R.id.ll_follow);
            isFollow(followIv, followTv, msg.getData().getIsreadisattention());
            followLl.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (Cache.LoginVer(mContext))
                        return;
                    readingDetailsPresenter.follow(String.valueOf(msg.getData().getIsattention() + 1), new CallBackColonyContract.OnOperation() {
                        @Override
                        public void OperationCallBack(String index) {
                            int status = msg.getData().getIsattention();
                            if (status == 1) {
                                status = 0;
                            } else {
                                status = 1;
                            }
                            msg.getData().setIsattention(status);
                            isFollow(followIv, followTv, String.valueOf(msg.getData().getIsattention()));
                        }
                    });
                }
            });
        } else {
            perLL.setVisibility(View.GONE);
        }
        myNote = (TextView) noteView.findViewById(R.id.et_my_note);
        editBtn.setOnClickListener(this);
        return noteView;
    }

    private String bookstatus;//首页图书状态
    private String status_type;//个人中心图书状态

    @Override
    public void onSuccess(BookDetailsBean msg) {
        first = false;
        this.msg = msg;
        bookstatus = msg.getData().getBookstatus();
        status_type = msg.getData().getStatus_type();
        Log.e("status_type", "status_type=" + status_type);
        generatingLayout();
    }

    boolean operationbo = false;

    @Override
    public void onOperationSuccess(AppItem msg) {
        if (operationbo && STATUS.equals("1")) {
            AlertUtils.initMsgDialog(mContext, new CallBackColonyContract.OnMSG() {
                @Override
                public void call() {
                    String phoneNo = "";
                    if (status_type.equals("6")) {
                        phoneNo = ReadingDetailsActivity.this.msg.getData().getBook_read_user_mobile();
                    } else {
                        phoneNo = ReadingDetailsActivity.this.msg.getData().getCurrentuserphone();
                    }
                    Intent phoneIntent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phoneNo));
                    phoneIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(phoneIntent);
                }

                @Override
                public void msg() {
                    checkIM(new CallBackColonyContract.OnCheck() {
                        @Override
                        public void check() {
                            initFind();
                        }
                    });

                }
            });
        } else if (STATUS.equals("6")) {
            startActivity(MyReadingActivity.class);
            App.getApplication().exitRead();

        } else if (STATUS.equals("7")) {
            STATUS = "5";
        }
        operationbo = false;
//        ToastUtil.show(mContext, msg.msg);
        onRefreshJudge = true;
        readingDetailsPresenter.initReadingDetails(mContext);
    }

    @Override
    public void onShowError(String msg) {

    }

    public void generatingLayout() {
        if (onRefreshJudge) {
            mSwipeRefreshLayout.setRefreshing(false);
            nullAdapter.setEnableLoadMore(true);
            nullAdapter.removeHeaderView(basicView);
            if (pager_Judge) {
                nullAdapter.removeHeaderView(ownerView);
            } else {
                nullAdapter.removeHeaderView(noteView);
            }
            onRefreshJudge = false;
        }
        if (nullAdapter == null) {
            nullAdapter = new NullAdapter();
        }
//        nullAdapter.openLoadAnimation();

        mSwipeRefreshLayout.setOnRefreshListener(this);
        nullAdapter.addHeaderView(getBasicView());
        isCollection(collectionImg, collectionText, String.valueOf(msg.getData().getIscollection()));
        if (pager_Judge) {
            nullAdapter.addHeaderView(getOwnerView());
            initHomeEntry();
        } else {
            nullAdapter.addHeaderView(getMyNoteView());
            initPeronalEntry();
        }
        mRecyclerView.setAdapter(nullAdapter);
//        mRecyclerView.smoothScrollToPosition(0);
    }

    void showUser(String userId) {
        Bundle b = new Bundle();
        b.putString(Cache.USER_ID, userId);
        b.putString("phone", "");
        startActivity(PersonalHomePageActivity.class, b);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rel_location://导航
                if (AmapUtil.isGaode() || AmapUtil.isBaidu()) {
                    AlertUtils.initNavigationDialog(this, new CallBackColonyContract.OnNavigation() {
                        @Override
                        public void gaode() {
                            AmapUtil.goToGaodeNaviActivity(mContext, "同文同书", msg.getData().getNow_book_postition(), msg.getData().getLatitude(), msg.getData().getLongitude(), "1", "0");
                        }

                        @Override
                        public void baidu() {
                            AMapLocation location = readingDetailsPresenter.getAMapLocation();
                            AmapUtil.goToBaiduNaviActivity(mContext, location.getLatitude(), location.getLongitude(), Double.valueOf(msg.getData().getLatitude()), Double.valueOf(msg.getData().getLongitude()), "driving");
                        }
                    });
                } else {
                    ToastUtil.show(mContext, "您没有安装任何导航软件");
                }
                break;
            case R.id.ll_note_edit://写笔记
                if (Cache.LoginVer(mContext))
                    return;
                Bundle b = new Bundle();
                b.putString("type", "note");
                b.putInt("textId", R.string.reading_note);
                b.putInt("textHint", R.string.note_hint);
                b.putString("text", myNote.getText().toString().trim());
                startActivity(PublicTextActivity.class, b);
                break;
            case R.id.ll_operation://操作图书
                if (Cache.LoginVer(mContext))
                    return;
                if (operation_Judge) {
                    operationbo = true;
                    if (STATUS.equals("0")) {
                        if (msg.getData().getIs_mark_book_user().equals("1")) {
                            AlertUtils.initMsgDialog(mContext, new CallBackColonyContract.OnMSG() {
                                @Override
                                public void call() {
                                    String phoneNo = "";
                                    if (status_type.equals("6")) {
                                        phoneNo = ReadingDetailsActivity.this.msg.getData().getBook_read_user_mobile();
                                    } else {
                                        phoneNo = ReadingDetailsActivity.this.msg.getData().getCurrentuserphone();
                                    }
                                    Intent phoneIntent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phoneNo));
                                    phoneIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                    startActivity(phoneIntent);
                                }

                                @Override
                                public void msg() {
                                    checkIM(new CallBackColonyContract.OnCheck() {
                                        @Override
                                        public void check() {
                                            initFind();
                                        }
                                    });

                                }
                            });
                        }
                    } else if (STATUS.equals("1")) {
                        if (Cache.getUser().getData().getUser_status().equals("2")) {
                            AlertUtils.showAgainShare(mContext, "实名认证后才能进去哦~", "稍后认证", "立即认证", 2, new CallBackColonyContract.OnDiyClick() {
                                @Override
                                public void left() {

                                }

                                @Override
                                public void right() {
                                    startActivity(RealNameAuthenticationActivity.class);
                                }
                            });
                            return;
                        } else if (Cache.getUser().getData().getMoney().equals("0")) {
                            AlertUtils.showAgainShare(mContext, "一丢丢押金就能免费读书百万本儿~", "稍后缴", "立即缴", 2, new CallBackColonyContract.OnDiyClick() {
                                @Override
                                public void left() {

                                }

                                @Override
                                public void right() {
                                    startActivity(RealNameAuthenticationActivity.class);
                                }
                            });
                            return;
                        }
                        AlertUtils.showAgainShare(mContext, "阅读书籍将消耗您" + Cache.getUser().getData().getMark_dou_num() + "颗书豆，是否继续？", "取消", "继续", 2, new CallBackColonyContract.OnDiyClick() {
                            @Override
                            public void left() {

                            }

                            @Override
                            public void right() {
                                readingDetailsPresenter.operationBook();
                            }
                        });
                    } else if (STATUS.equals("6")) {
                        AlertUtils.showAgainShare(mContext, "小伙伴等急了哦，快点交给他吧~", "稍后转交", "立即转交", 2, new CallBackColonyContract.OnDiyClick() {
                            @Override
                            public void left() {

                            }

                            @Override
                            public void right() {
                                readingDetailsPresenter.operationBook();
                            }
                        });
                    } else if (STATUS.equals("2")) {
                        Bundle sha = new Bundle();
                        sha.putString("bookid", getBookId());
                        sha.putString("bookname", msg.getData().getBookid());
                        sha.putString("bookname1", msg.getData().getBookname());
                        sha.putString("bookinfo", msg.getData().getBookdesc());
                        sha.putString("booktype", msg.getData().getBooktype());
                        sha.putString("old_degree", msg.getData().getBook_new_old());
                        sha.putString("money", msg.getData().getMoney());
                        sha.putString("bookpicurl", msg.getData().getBookpicurl());
                        startActivity(AgainShareBookActivity.class, sha);
                    } else if (STATUS.equals("5")) {
                        toAgainShare();
                    } else if (STATUS.equals("4")) {
                        Bundle cancelB = new Bundle();
                        cancelB.putString("bookid", bookId);
                        cancelB.putString("logid", msg.getData().getLogid());
                        startActivity(CancelReservationActivity.class, cancelB);
                    }
                }
                break;
            case R.id.ll_call: //用intent启动拨打电话
                Intent phoneIntent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + msg.getData().getCurrentuserphone()));
                phoneIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(phoneIntent);
                break;
            case R.id.ll_renewal://续期

                AlertUtils.showAgainShare(mContext, "书籍续期将消耗您" + Cache.getUser().getData().getRenewal_dou_num() + "颗书豆，是否继续？", "取消", "继续", 2, new CallBackColonyContract.OnDiyClick() {
                    @Override
                    public void left() {

                    }

                    @Override
                    public void right() {
                        STATUS = "7";
                        readingDetailsPresenter.operationBook();
                    }
                });
                break;
            case R.id.ll_collection://收藏
                if (Cache.LoginVer(mContext))
                    return;
                boolean st;
                if (msg.getData().getIscollection() == 1) {
                    st = true;
                } else {
                    st = false;
                }
                readingDetailsPresenter.collection(st, new CallBackColonyContract.OnOperation() {
                    @Override
                    public void OperationCallBack(String index) {
                        int status = msg.getData().getIscollection();
                        if (status == 1) {
                            status = 0;
                        } else {
                            status = 1;
                        }
                        msg.getData().setIscollection(status);
                        isCollection(collectionImg, collectionText, String.valueOf(msg.getData().getIscollection()));
                    }
                });

                break;
            case R.id.ll_msg://聊天
                checkIM(new CallBackColonyContract.OnCheck() {
                    @Override
                    public void check() {
                        initFind();
                    }
                });

                break;
            case R.id.title_share://分享
                ShareUtils.initBooksDialog(mContext,
                        "附近的书免费看，快来一起阅读吧！好友" + Cache.getUser().getData().getNickname() + "邀请您加入同文同书",
                        Cache.getUser().getData().getShare_book() + getBookId(),
                        msg.getData().getBookpicurl(),
                        "您的好友推荐了一本图书《" + msg.getData().getBookname() + "》快来阅读吧~");

                break;
            default:
                break;
        }
    }

    void toAgainShare() {
        AlertUtils.showAgainShare(mContext, "读完之后需要重新分享书籍，\n是否读完？", "继续阅读  ", "去分享", 2, new CallBackColonyContract.OnDiyClick() {
            @Override
            public void left() {

            }

            @Override
            public void right() {
                Bundle b = new Bundle();
                b.putString("bookid", getBookId());
                b.putString("bookname", msg.getData().getBookid());
                b.putString("bookname1", msg.getData().getBookname());
                b.putString("bookinfo", msg.getData().getBookdesc());
                b.putString("booktype", msg.getData().getBooktype());
                b.putString("old_degree", msg.getData().getBook_new_old());
                b.putString("money", msg.getData().getMoney());
                b.putString("bookpicurl", msg.getData().getBookpicurl());
                startActivity(AgainShareBookActivity.class, b);
            }
        });

    }

    void initHomeEntry() {
        whenLongText.setVisibility(View.VISIBLE);
        share.setVisibility(View.VISIBLE);
        switch (bookstatus) {
            case "1"://被预约、
                operation_Judge = false;
                status.setText("被预约");
                operationText.setText("被预约");
                if (msg.getData().getIs_mark_book_user().equals("1")) {
                    STATUS = "0";
                    operation_Judge = true;
                    operationText.setText("联系TA");
                    ivOperation.setImageResource(R.drawable.call);
                    whenLongText.setText("你不是要一睹为快嘛，麻溜去取书吧，限定24小时之内哦~");
                } else {
                    operationText.setTextColor(this.getResources().getColor(R.color.share_read_over));
                    ivOperation.setImageResource(R.drawable.reading_operation);
                    whenLongText.setText("下手太慢啦，此书已被预约~");
                }
                hideContract();
                break;
            case "2"://在读
                operation_Judge = false;
                operationText.setText("在读");
                status.setText("在读");
                operationText.setTextColor(this.getResources().getColor(R.color.share_read_over));
                whenLongText.setText("读者正在阅读这本书，再看看其他书籍吧");
                hideContract();

                break;
            case "3"://空闲
                STATUS = "1";
                operation_Judge = true;
                operationText.setText("我要读书");
                status.setText("空闲中");
                whenLongText.setText("确定阅读后请在24小时内领她回家");
                hideContract();
                break;
            default:
                break;
        }
    }

    void isFollow(ImageView iv, TextView tv, String status) {
        if (status.equals("0")) {
            iv.setImageResource(R.drawable.xin);
            tv.setText("加关注");
        } else {
            iv.setImageResource(R.drawable.xined);
            tv.setText("已关注");
        }
    }

    void isCollection(ImageView iv, TextView tv, String status) {
        if (status.equals("0")) {
            iv.setImageResource(R.drawable.follow);
            tv.setText("收藏");
        } else {
            iv.setImageResource(R.drawable.followed);
            tv.setText("已收藏");
        }
    }

    void initPeronalEntry() {
        share.setVisibility(View.GONE);
        whenLongText.setVisibility(View.GONE);
        operation_Judge = true;
        switch (status_type) {
            case "1"://预约、
                renewalRel.setVisibility(View.GONE);
                callRel.setVisibility(View.VISIBLE);
                STATUS = "4";
                operationText.setText("取消预约");
                status.setText("预约");
                reading_time.setText("预约时间:" + msg.getData().getOrdertime() + "\n预约到期时间:" + msg.getData().getOrderendtime());
                relNote.setVisibility(View.GONE);
                showContract();
                break;
            case "2"://在读
                renewalRel.setVisibility(View.VISIBLE);
                callRel.setVisibility(View.GONE);
                STATUS = "5";
                operationText.setText("我已读完");
                status.setText("阅读中");
                renewal.setVisibility(View.VISIBLE);
                reading_time.setText("预约时间:" + msg.getData().getOrdertime() + "\n阅读时间:" + msg.getData().getReadingtime() + "\n到期时间:" + msg.getData().getOut_time());
                relNote.setVisibility(View.VISIBLE);
                hideContract();
                break;
            case "3"://读完
                renewalRel.setVisibility(View.GONE);
                callRel.setVisibility(View.VISIBLE);
                operation_Judge = false;
                operationText.setText("已读完");
                status.setText("已读完");
                operationText.setTextColor(this.getResources().getColor(R.color.share_read_over));
                whenLongText.setText("已读完");
                reading_time.setText("阅读时间:" + msg.getData().getReadingtime() + "\n读完时间:" + msg.getData().getReadingendtime());
                relNote.setVisibility(View.VISIBLE);
                hideContract();
                break;
            case "4"://取消预约
                renewalRel.setVisibility(View.GONE);
                callRel.setVisibility(View.VISIBLE);
                operation_Judge = false;
                operationText.setText("已取消");
                operationText.setTextColor(this.getResources().getColor(R.color.share_read_over));
                whenLongText.setText("已取消");
                relNote.setVisibility(View.VISIBLE);
                hideContract();
                break;
            case "5"://空闲
                STATUS = "2";
                renewalRel.setVisibility(View.GONE);
                callRel.setVisibility(View.VISIBLE);
                operationText.setText("再次分享");
                status.setText("空闲");
                reading_time.setText("阅读时间:" + msg.getData().getReadingtime() + "\n读完时间:" + msg.getData().getReadingendtime());
                whenLongText.setText("已空闲了" + msg.getData().getBook_time());
                relNote.setVisibility(View.VISIBLE);
                hideContract();
                break;
            case "6"://被预约
                renewalRel.setVisibility(View.GONE);
                callRel.setVisibility(View.VISIBLE);
                status.setText("被预约");
                STATUS = "6";
                operationText.setText("转交");
                relNote.setVisibility(View.VISIBLE);
                showContract();
                break;
            default:
                break;
        }
    }

    void hideContract() {
        call.setVisibility(View.GONE);
        chat.setVisibility(View.GONE);
        v1.setVisibility(View.GONE);
        v2.setVisibility(View.GONE);
    }

    void showContract() {
        call.setVisibility(View.VISIBLE);
        chat.setVisibility(View.VISIBLE);
        v1.setVisibility(View.VISIBLE);
        v2.setVisibility(View.VISIBLE);
    }

    @Override
    public void onRefresh() {
        onRefreshJudge = true;
        readingDetailsPresenter.initReadingDetails(mContext);
    }

    void initFind() {
        //创建请求列表
        List<TIMAddFriendRequest> reqList = new ArrayList<TIMAddFriendRequest>();
        final String id;
        if (status_type.equals("6")) {
            id = ReadingDetailsActivity.this.msg.getData().getBook_read_user_mobile();
        } else {
            id = ReadingDetailsActivity.this.msg.getData().getCurrentuserphone();
        }
        //添加好友请求
        TIMAddFriendRequest req = new TIMAddFriendRequest(id);
        req.setAddrSource("AddSource_Type_Android");
        req.setRemark(msg.getData().getCurrentusernick());

        reqList.add(req);

        //申请添加好友
        TIMFriendshipManagerExt.getInstance().addFriend(reqList, new TIMValueCallBack<List<TIMFriendResult>>() {
            @Override
            public void onError(int code, String desc) {
                //错误码code和错误描述desc，可用于定位请求失败原因
                //错误码code列表请参见错误码表
                Log.e(TAG, "addFriend failed: " + code + " desc" + desc);
            }

            @Override
            public void onSuccess(List<TIMFriendResult> result) {
                Log.e(TAG, "addFriend succ");

                boolean b = false;
                for (TIMFriendResult res : result) {
                    b = true;
//                    Log.e(TAG, "identifier: " + res.getIdentifer() + " status: " + res.getStatus());

                }
                if (b) {
                    List<String> users = new ArrayList<String>();
                    users.add(id);
                    //获取好友资料
                    TIMFriendshipManager.getInstance().getUsersProfile(users, new TIMValueCallBack<List<TIMUserProfile>>() {
                        @Override
                        public void onError(int code, String desc) {
                            //错误码code和错误描述desc，可用于定位请求失败原因
                            //错误码code列表请参见错误码表
                            Log.e("shi", "getFriendsProfile failed: " + code + " desc");
                        }

                        @Override
                        public void onSuccess(List<TIMUserProfile> result) {

                            String name = result.get(0).getNickName().isEmpty() ? result.get(0).getIdentifier() : result.get(0).getNickName();

                            String imageUrl = result.get(0).getFaceUrl().isEmpty() ? "" : result.get(0).getFaceUrl();

                            ChatActivity.navToChat(mContext, id, TIMConversationType.C2C, imageUrl, name);
                        }
                    });
                } else {

                }
            }
        });

    }
}
